package algorithm;

import java.util.HashMap;
import java.util.Map;

public class T00076 {
    public static void main(String[] args) {
        String s = "ADOBECODEBANC";
        String t = "BANC";
        System.out.println(new Solution().minWindow(s, t));
    }

    static class Solution {
        public String minWindow(String s, String t) {
            Map<Character, Integer> need = new HashMap<>();
            Map<Character, Integer> window = new HashMap<>();
            for (int i = 0; i < t.length(); i ++) {
                char c = t.charAt(i);
                need.put(c, need.getOrDefault(c, 0) + 1);
            }

            int start = 0, left = 0, right = 0, valid = 0, len = Integer.MAX_VALUE;
            while (right < s.length()) {
                char c = s.charAt(right);
                if (need.containsKey(c)) {
                    window.put(c, window.getOrDefault(c, 0) + 1);
                    if (window.get(c).equals(need.get(c))) {
                        valid ++;
                    }
                }
                right ++;

                while (valid == need.size()) {
                    if (right - left < len) {
                        len = right - left;
                        start = left;
                    }
                    char d = s.charAt(left);
                    if (need.containsKey(d)) {
                        if (need.get(d).equals(window.get(d))) {
                            valid --;
                        }
                        window.put(d, window.get(d) - 1);
                    }
                    left ++;
                }
            }
            return len == Integer.MAX_VALUE ? "" : s.substring(start, start + len);
        }
    }
}
